package com.tc.property.config.handler;

import com.alibaba.fastjson.JSON;
import com.tc.property.config.model.ConfigContext;
import com.tc.property.config.model.ConfigItem;
import org.apache.commons.collections.CollectionUtils;

import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class DefaultConfigSourceChangedHandler implements IConfigSourceChangedHandler {

	private ConfigContext configContext;

	private List<IConfigChangedHandler> handlers;

	public DefaultConfigSourceChangedHandler(ConfigContext configContext, List<IConfigChangedHandler> handlers) {
		super();
		this.configContext = configContext;
		this.handlers = handlers;
	}

	@Override
	public void update(Map<String, ConfigItem> map) {
		ConfigContext previous = deepCloneByJson(configContext);

		configContext.merge(map);

		Set<String> oldKeySet = previous.getCfgcenterItemMap().keySet();
		Set<String> newKeySet = map.keySet();
		Collection<String> subtractedKeySet = CollectionUtils.subtract(oldKeySet, newKeySet);
		//移除了删除的key
		for (String key : subtractedKeySet) {
			configContext.remove(key);
		}
		configContext.setCfgcenterItemMap(map);

		if (handlers != null && handlers.size() > 0) {
			for (IConfigChangedHandler iconfigChangedHandler : handlers) {
				iconfigChangedHandler.handle(previous, configContext);
			}
		}
	}

	private static ConfigContext deepCloneByJson(ConfigContext src) {
		return JSON.parseObject(JSON.toJSONString(src), ConfigContext.class);
	}

}
